package com.ease.business.dpi.service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.math.RandomUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;

import com.ease.common.util.DateFormatUtil;
import com.ease.dao.JdbcTemplateDataAccessObject;
import com.ease.dao.jdbctemplate.rowmapper.ParameterizedBeanPropertyRowMapper;
import com.obas.model.business.AaaCustomer;
import com.obas.model.business.DpiSession;
import com.obas.test.ApplicationContextUserContextTest;

public class DpiDataSimulator extends ApplicationContextUserContextTest {
	int len = 100;
	@Autowired
	private JdbcTemplateDataAccessObject jdbcTemplateDataAccessObject;

	// @Autowired
	// private DpiSessionAccessService dpiSessionAccessService;

	// @Test
	public void simulate() {

		// List<AaaCustomer> aaaCustomers =
		// jdbcTemplateDataAccessObject.find("SELECT o.USERNAME, O.AREANO FROM I_AAA_CUSTOMER O WHERE O.VERSION IS NOT NULL",
		// new ParameterizedBeanPropertyRowMapper<AaaCustomer>() {
		// });
		List<AaaCustomer> aaaCustomers = jdbcTemplateDataAccessObject.find("SELECT o.USERNAME, O.AREANO FROM I_AAA_CUSTOMER O WHERE O.VERSION IS NOT NULL",
				ParameterizedBeanPropertyRowMapper.newInstance(AaaCustomer.class));

		Date date = new Date();

		for (int i = 0; i < len; i++) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.MINUTE, i);
			Date batchDate = calendar.getTime();
			data(aaaCustomers, batchDate);

		}
	}

	public void data(List<AaaCustomer> aaaCustomers, Date batchDate) {

		long endTime = batchDate.getTime();

		if (null != aaaCustomers) {
			// List<DpiSession> dpiSessions = new ArrayList<DpiSession>();
			for (AaaCustomer aaaCustomer : aaaCustomers) {
				DpiSession dpiSession = new DpiSession();
				// dpiSessions.add(dpiSession);

				dpiSession.setSubscriberId(aaaCustomer.getUsername());// SUBSCRIBERID VARCHAR2(255) Y
																		// 登录名或IP（如果以PPPOE方式上网，则显示用户名，其它为IP）（10.11.0.1或者wangming）
				dpiSession.setClientIp(randomIp());// CLIENTIP VARCHAR2(255) Y 用户IP（4-0A584264 ）
				dpiSession.setServerIp(randomIp());// SERVERIP VARCHAR2(255) Y 服务器IP（4-0A584264 ）
				dpiSession.setEndTime(endTime);// ENDTIME NUMBER Y 结束时间
				dpiSession.setHost(randomIp());// HOST VARCHAR2(255) Y HOST(暂时留空)
				// PROTOCOLTYPE NUMBER Y 传输协议（4:表示TCP， 5:标识UDP）
				dpiSession.setAppId((short) 29);// APPID NUMBER Y 应用ID
				// OUTSTREAM NUMBER Y 上行流量，单位为KB
				dpiSession.setInStream(randomNumber());// INSTREAM NUMBER Y 下行流量，单位为KB
				// DELAYCTD NUMBER Y 网络时延(用户-观测点) 单位为ms
				// DELAYDTS NUMBER Y 网络时延(观测点-用户) 单位为ms
				// OUTSTREAMPKTCNT NUMBER Y 上行报文数
				// INSTREAM_PKTCNT NUMBER Y 下行报文数
				// OUTRETPACKETCNT NUMBER Y 上行重传报文数
				// INRETPACKETCNT NUMBER Y 下行重传报文数
				// OUTMISSCODEPACKETCNT NUMBER Y 上行误码报文数（暂时留空）
				// INMISSCODEPACKETCNT NUMBER Y 下行误码报文数（暂时留空）
				// ZEROWINDOWCOUNT NUMBER Y TCP零窗口
				// IPANALYZEPACKETCNT NUMBER Y IP分析包数（暂时留空）
				// TCPLINKFAILCOUNT NUMBER Y TCP连接失败
				// DELAYJITTER NUMBER Y 时延抖动
				// ENDTIMEDATE DATE Y ENDTIME-DATE
				// dpiSessionAccessService.create(dpiSession);
				dpiSession.setAreaNo(aaaCustomer.getAreaNo());
				dpiSession.setBatchTimestamp(batchDate);
				jdbcTemplateDataAccessObject
						.create("INSERT INTO I_DPI_SESSION(ID,SUBSCRIBERID,CLIENTIP,SERVERIP,ENDTIME,HOST,APPID,INSTREAM,AREANO,BATCHTIMESTAMP)VALUES(SEQ_I_DPI_SESSION.NEXTVAL,:subscriberId,:clientIp,:serverIp,:endTime,:host,:appId,:inStream,:areaNo,:batchTimestamp)",
								new BeanPropertySqlParameterSource(dpiSession));
			}
			//
			// MapParameter mapParameter = new MapParameter();
			// mapParameter.put("batchTimestamp", date);
			// String minutesql =
			// "INSERT INTO C_KPISERVING(ID, AREANO, KPITYPE_ID, SERVINGTYPE_ID, MAX, AVG, MIN, AMOUNT, BATCHTIMESTAMP) SELECT SEQ_C_KPISERVING.NEXTVAL, O.* FROM (SELECT T.AREANO, 11, T.APPID,  MAX(T.INSTREAM),AVG(T.INSTREAM),MIN(T.INSTREAM),COUNT(0),:batchTimestamp FROM I_DPI_SESSION T WHERE BATCHTIMESTAMP=:batchTimestamp GROUP BY T.AREANO, T.APPID) O";
			// jdbcTemplateDataAccessObject.execute(minutesql, mapParameter);
			//
			String batchTimestamp = DateFormatUtil.toDatetimeString(batchDate);
			String minutesql = "INSERT INTO C_KPISERVING_MINUTE(ID, AREANO, KPITYPE_ID, SERVINGTYPE_ID, MAX, AVG, MIN, AMOUNT, BATCHTIMESTAMP) SELECT SEQ_C_KPISERVING_MINUTE.NEXTVAL, O.* FROM (SELECT T.AREANO, 11, T.APPID,  MAX(T.INSTREAM),AVG(T.INSTREAM),MIN(T.INSTREAM),COUNT(0),TO_DATE('"
					+ batchTimestamp + "','yyyy-mm-dd hh24:mi:ss') FROM I_DPI_SESSION T WHERE BATCHTIMESTAMP=TO_DATE('" + batchTimestamp + "','yyyy-mm-dd hh24:mi:ss') GROUP BY T.AREANO, T.APPID) O";
			jdbcTemplateDataAccessObject.getJdbcTemplate().execute(minutesql);

			// MapParameter parameter = new MapParameter();
			// parameter.put("dpiSessions", dpiSessions);
			// String content = FreeMarkerUtil.processFile(DpiDataSimulator.class, "dpiSession.ftl", parameter);
			// FileUtil.write("D:/repository/workspaces/googlecode_obas_java/com.obas.application.java/dpidata", "dpi_"
			// + DateFormatUtil.toDatatimeNumberString(date) + ".txt", content);

		}
	}

	@Test
	public void accumulative() {

		Date date = DateFormatUtil.toDatetime("2013-05-24 22:36:55");

		for (int i = 0; i < len; i++) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.MINUTE, i);
			Date batchDate = calendar.getTime();
			accumulativeData(batchDate);
		}

	}

	public void accumulativeData(Date batchDate) {
		String batchTimestamp = DateFormatUtil.toDatetimeString(batchDate);
		String minutesql = "INSERT INTO C_KPISERVING_MINUTE_ACC (ID, AREANO, SERVINGTYPE_ID, KPITYPE_ID, MAX, AVG, MIN, AMOUNT, BATCHTIMESTAMP) SELECT SEQ_C_KPISERVING_MINUTE_ACC.NEXTVAL, O.* FROM (SELECT T.AREANO, t.servingtype_id, t.kpitype_id ,sum(T.max*T.amount)/sum(amount), sum(T.avg*T.amount)/sum(amount), sum(T.min*T.amount)/sum(amount), sum(amount) amount_acc, TO_DATE('"
				+ batchTimestamp
				+ "', 'yyyy-mm-dd hh24:mi:ss') FROM C_KPISERVING_MINUTE T WHERE BATCHTIMESTAMP <= to_date('"
				+ batchTimestamp
				+ "', 'yyyy-mm-dd hh24:mi:ss') GROUP BY T.AREANO,t.servingtype_id, t.kpitype_id) O";
		jdbcTemplateDataAccessObject.getJdbcTemplate().execute(minutesql);
	}

	public static String randomIp() {
		return String.valueOf(RandomUtils.nextInt(2147483647));
	}

	public static int randomNumber() {
		return RandomUtils.nextInt(10000);
	}

}
